<template>
  <div id="map" class="map" tabindex="0"></div>
</template>

<script>
import "ol/ol.css";
import Map from "ol/Map";
import OSM from "ol/source/OSM";
import TileLayer from "ol/layer/Tile";
import View from "ol/View";

import { getTyphoonData } from '../api/typhoon.js';
import Feature from 'ol/Feature';
import { Vector as VectorSource} from 'ol/source';
import { Vector as VectorLayer } from 'ol/layer';
import { MultiLineString, Point } from 'ol/geom';
import { fromLonLat } from 'ol/proj';
import {Circle, Fill, Style} from 'ol/style';


export default {
  name: "HelloWorld",
  data (){
    return {
        map: null 
    }
  },
  methods: {
       getTyphoonData: async function(){
        const { data } = await getTyphoonData();
        console.log( data );
        let points = data[0].points;
        let features = [];
        let positions = [];
        for(let i = 0; i < points.length; i++) {
            let position = [points[i].lng, points[i].lat];
            let featurePoint = new Feature({
                geometry: new Point(fromLonLat(position))
            });
            featurePoint.setStyle(new Style({
              image: new Circle({
                fill: new Fill({
                  color: this.judgeColorByWindLevels(points[i].strong)
                }),
                radius: 4
              })
            }));
            if(i != points.length - 1) {
              let nextPosition = [points[i + 1].lng, points[i + 1].lat];
              positions.push([fromLonLat(position), fromLonLat(nextPosition)]);
            }
            features.push(featurePoint);
        }

        let featureLine = new Feature({
          geometry: new MultiLineString(positions)
        })
        features.push(featureLine);
        // 矢量图层
        let layer = new VectorLayer();
        // 矢量数据源
        let source = new VectorSource();

        source.addFeatures(features);
        layer.setSource(source);
        this.map.addLayer(layer);
      },
      judgeColorByWindLevels: function(windLevel){
        var map = {
          "热带风暴": "red",
          "热带低压": "blue",
          "强热带风暴": "green",
          "台风": "orange",
          "强台风": "yellow",
          "超强台风": "salmon"
        };

        return map[windLevel];
      }
  },
  created() {
  },
  mounted(){
    
    this.map = new Map({
      layers: [
        new TileLayer({
          source: new OSM(),
        }),
      ],
      target: "map",
      view: new View({
        center: [0, 0],
        zoom: 2,
      }),
    });

    this.getTyphoonData();
    
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

 .map {
        width: 100%;
        height:100vh;
      }
     
      #map:focus {
        outline: #4A74A8 solid 0.15em;
      }
</style>
